package org.dtrd.modules.system.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.system.entity.bean.qiyeweixin.*;
import org.dtrd.modules.system.entity.po.DtrdEntRdRobot;
import org.dtrd.modules.system.entity.request.RobotListRequest;
import org.dtrd.modules.system.service.IDtrdEntRdRobotService;
import org.dtrd.modules.system.util.qywx.RobotUtil;
import org.dtrd.modules.util.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.*;

/**
 * @author qr
 * @date 2022/3/7 09:51
 */
@Api(tags = "企微机器人")
@RestController
@RequestMapping("/sys/robot/")
public class RobotController extends BaseController {

    @Autowired
    private IDtrdEntRdRobotService robotService;
    @Autowired
    private BaseCommonService baseCommonService;

    @ApiOperation("推送机器人消息")
    @PostMapping("send")
    public Result<?> sendRobotMessage(@RequestBody RobotMessageRequest request){
        Integer msgType = request.getMsgType();
        Integer robotId = request.getRobotId();
        if (robotId == null || msgType == null) {
            return error(STATE_PARAMS_MISSING);
        }
        Constant.RobotMsgType robotMsgType = Constant.RobotMsgType.valueOf(msgType);

        if (robotMsgType == null) {
            return error(STATE_PARAMS_ERROR);
        }
        String webhookurl = robotService.getRobotWebhookurl(robotId);
        // 发送消息
        RobotMessage msg = RobotUtil.sendMsg(robotMsgType, request, webhookurl);
        // 保存系统日志
        String username = ShiroUtil.getUserName();
        String logContent = String.format("推送机器人消息, 推送人: %s", username);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(msg);
    }


    @ApiOperation("推送机器人消息-打卡提醒")
    @GetMapping("signin/remain")
    public Result<?> signinRemain(@RequestParam Integer robotId,
                          @RequestParam Integer recordType,
                          @RequestParam Integer subType,
                          @RequestParam Integer patientId){
        Constant.RecordType type = Constant.RecordType.valueOf(recordType);
        if (type == null) {
            return error(STATE_PARAMS_ERROR);
        }
        String webhookurl = robotService.getRobotWebhookurl(robotId);
        RobotMessage message = RobotUtil.signinRemain(webhookurl, type, subType, patientId);
        // 保存系统日志
        String username = ShiroUtil.getUserName();
        String logContent = String.format("推送机器人打卡提醒, 推送人: %s", username);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(message);
    }

    @ApiOperation(value = "获取可上传文件的类型", response = MsgType.class)
    @GetMapping("msgType")
    public Result<?> getMsgTypes(){
        ArrayList<MsgType> msgTypes = new ArrayList<>();
        for (Constant.RobotMsgType value : Constant.RobotMsgType.values()) {
            MsgType msgType = new MsgType(value.getType(), value.getName());
            msgTypes.add(msgType);
        }
        return Result.OK(msgTypes);
    }

    @ApiOperation("上传文件获取mediaId")
    @PostMapping("upload")
    public Result<?> saveOrUpdate(@RequestParam MultipartFile media,
                                  @RequestParam Integer robotId){
        DtrdEntRdRobot robot = robotService.getById(robotId);
        if (robot == null || StrUtil.isBlank(robot.getWebhookkey())) {
            return Result.error("无效的robotId");
        }
        String mediaId = RobotUtil.uploadFile(media, robot.getWebhookkey());
        String logContent = String.format("上传文件给机器人, robotId: %d", robotId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(mediaId);
    }

//    @ApiOperation(value = "查询企业微信机器人记录表详情", response = RobotDetail.class)
//    @GetMapping("get")
//    public Result<?> getRobot(@RequestParam Integer id){
//        RobotDetail info = robotService.getRobot(id);
//        String logContent = String.format("查询企业微信机器人记录表详情，查询id：%d", id);
//        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
//        return Result.OK(info);
//    }

    @ApiOperation(value = "查询企业微信机器人记录表列表", response = RobotListInfo.class)
    @GetMapping("list")
    public Result<?> getRobotList(RobotListRequest request){
        List<RobotListInfo> list = robotService.getRobotList(request);
        String logContent = String.format("查询企业微信机器人记录表列表, 查询条件: %s", request);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(list);
    }

//    @ApiOperation(value = "分页查询企业微信机器人记录表列表", response = RobotListInfo.class)
//    @PostMapping("page")
//    public Result<?> getRobotList(@RequestBody RobotPageRequest request){
//        handlePageRequest(request);
//        IPage<RobotListInfo> page = robotService.pageRobot(request);
//        String logContent = String.format("分页查询企业微信机器人记录表列表, 查询条件: %s", request);
//        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
//        JSONObject result = new JSONObject();
//        result.put("recordList", page.getRecords());
//        result.put("totalPage", page.getPages());
//        return Result.OK(result);
//    }

    @ApiOperation("新增或修改企业微信机器人记录表")
    @PostMapping("saveOrUpdate")
    public Result<?> saveOrUpdateRobot(@RequestBody RobotDetail dto){
        if (dto.getWebhookurl() == null || dto.getRobotName() == null) {
            return error(STATE_PARAMS_MISSING);
        }
        if (!robotService.isValidName(dto.getRobotName(), dto.getId())) {
            return Result.error("已存在同名机器人");
        }
        boolean result = robotService.saveOrUpdateRobot(dto);
        String logContent = String.format("新增或修改企业微信机器人记录表, 修改机器人: %s", dto.getRobotName());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除企业微信机器人记录表")
    @DeleteMapping("remove")
    public Result<?> removeRobot(@RequestParam Integer id){
        if(isIntParamInvalid(id)) {
            return error(STATE_PARAMS_MISSING);
        }
        boolean result = robotService.removeRobot(id);
        String logContent = String.format("删除企业微信机器人记录表, 删除id: %d", id);
        baseCommonService.addLog(logContent, OPERATE_TYPE_DELETE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }
}
